<template>
    <div style="padding: 20px;">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form ref="form" label-width="80px" :inline="true">
                <el-form-item label="用户搜索">
                    <el-input v-model="searchValue" placeholder="请输入用户名" clearable style="width:250px;" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                </el-form-item>
            </el-form>

        </el-card>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
            <el-popconfirm title="你确定要删除这些用户吗？" @confirm="batchDelete">
                <template #reference>
                    <el-button type="danger" size="default" icon="Delete"
                        :disabled="!deleteidList.length">批量删除</el-button>
                </template>
            </el-popconfirm>
            <el-table :data="userList" border class="user-table" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="80" align="center"></el-table-column>
                <el-table-column label="#" type="index" width="80" align="center"></el-table-column>
                <el-table-column label="用户id" width="80" align="center" prop="id"></el-table-column>
                <el-table-column label="用户名" width="150" align="center" prop="username"></el-table-column>
                <el-table-column label="昵称" width="150" align="center" prop="name"></el-table-column>
                <el-table-column label="用户角色" width="240" align="center" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="default" @click="assignRole(scope.row)">分配角色</el-button>
                        <el-button type="primary" size="default" @click="editUser(scope.row)">编辑</el-button>
                        <el-popconfirm title="你确定要删除此用户吗？" @confirm="deleteThisUser(scope.row)">
                            <template #reference>
                                <el-button type="danger" size="default">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="PageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
                :background="true" layout="  sizes,prev, pager, next, ->,jumper,total" :total="total" />
        </el-card>
        <!-- 添加用户  抽屉-->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>{{ UserParams.id ? '编辑用户' : '添加用户' }}</h4>
            </template>
            <template #default>
                <el-form label-width="80px" :inline="false" :model="UserParams" :rules="rules" ref="formRef">
                    <el-form-item label="用户姓名" prop="username">
                        <el-input placeholder="请输入用户姓名" clearable style="width:250px;" v-model="UserParams.username" />
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="name">
                        <el-input placeholder="请输入用户昵称" clearable style="width:250px;" v-model="UserParams.name" />
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" v-if="!UserParams.id">
                        <el-input placeholder="请输入用户密码" clearable style="width:250px;" v-model="UserParams.password" />
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button type="primary" size="default" @click="handleSubmit">提交</el-button>
                <el-button type="primary" size="default" @click="handleCancel">取消</el-button>
            </template>
        </el-drawer>
        <!-- 分配角色  抽屉-->
        <el-drawer v-model="drawer1">
            <template #header>
                <h4>分配角色</h4>
            </template>
            <template #default>
                <el-form label-width="80px" :inline="false" :model="UserParams" :rules="rules" ref="formRef">
                    <el-form-item label="用户姓名" prop="username">
                        <el-input placeholder="请输入用户姓名" clearable style="width:250px;" v-model="UserParams.username"
                            disabled />
                    </el-form-item>
                    <el-form-item label="角色列表" size="normal">
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                            Check all
                        </el-checkbox>
                        <el-checkbox-group v-model="hasRoleList" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="role in allRoleList" :key="role.id" :label="role.id" :value="role">
                                {{ role.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                </el-form>
            </template>
            <template #footer>
                <el-button type="primary" size="default" @click="handleEditRoleSubmit">提交</el-button>
                <el-button type="primary" size="default" @click="handleCancel">取消</el-button>
            </template>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { addorupdateUser, deleteUser, deleteUserBatch, getRoleList, getUserList, setRole } from '@/api/acl/user'
import { useThrottle } from '@/utils/throttle'
import cloneDeep from 'lodash/cloneDeep';
import type { RoleData, SetRoleData, User } from '@/api/acl/user/type';
import { ElMessage, type CheckboxValueType } from 'element-plus';
import { nextTick } from 'vue';
import { onMounted, ref, watch } from 'vue';
import { useDebounce } from '@/utils/debounce';
let PageNo = ref(1)
let pageSize = ref(5)
let total = ref(0)
let searchValue = ref('')
let userList = ref<User[]>([])
let drawer = ref(false)
let drawer1 = ref(false)
let checkAll = ref(false)
let isIndeterminate = ref(true)
const formRef = ref()
let UserParams = ref<User>({
    username: '',
    name: '',
    password: ''
})
let hasRoleList = ref<RoleData[]>([])
let allRoleList = ref<RoleData[]>([])
let deleteidList = ref<number[]>([])
const search = () => {
    PageNo.value = 1
    getUserListData()
    searchValue.value = ''
}
// 获取用户列表数据
const getUserListData = useDebounce(async () => {
    while (true) {
        try {
            const res = await getUserList(PageNo.value, pageSize.value, searchValue.value)
            if (res.code == 200) {
                userList.value = res.data.records
                total.value = res.data.total
                break
            }
            else if (res.code == 201) {
                ElMessage.error(res.message)
                break
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}, 1000)
// 添加用户
const addUser = () => {
    UserParams.value.id = undefined
    drawer.value = true
    nextTick(() => {
        formRef.value.resetFields()
        clearUserParams()
    })
    console.log('添加用户')
}
// 批量删除
const batchDelete = async () => {
    while (true) {
        try {
            const res = await deleteUserBatch(deleteidList.value)
            if (res.code == 200) {
                ElMessage.success('删除成功')
                getUserListData()
                break
            }
            else if (res.code == 201) {
                ElMessage.error(res.message)
                break
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}
// 分配角色
const assignRole = useThrottle(async (row: User) => {
    UserParams.value = cloneDeep(row)
    while (true) {
        try {
            if (UserParams.value.id) {
                const res = await getRoleList(UserParams.value.id)
                if (res.code == 200) {
                    hasRoleList.value = res.data.assignRoles
                    allRoleList.value = res.data.allRolesList
                    drawer1.value = true
                    nextTick(() => {
                        formRef.value.validateField()
                    })
                    break
                }
                else if (res.code == 201) {
                    ElMessage.error(res.message)
                    break
                }
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}, 1000)
// 编辑用户
const editUser = (row: User) => {
    UserParams.value = JSON.parse(JSON.stringify(row))
    drawer.value = true
    nextTick(() => {
        formRef.value.validateField()
    })
}
// 删除用户
const deleteThisUser = useThrottle(async (row: User) => {
    while (true) {
        try {
            const res = await deleteUser(row.id as number)
            if (res.code == 200) {
                ElMessage.success('删除成功')
                getUserListData()
                break
            }
            else if (res.code == 201) {
                ElMessage.error(res.message)
                break
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}, 1000)
const clearUserParams = () => {
    UserParams.value = {
        username: '',
        name: '',
        password: ''
    }
}
// 验证用户名
const validateUsername = (_rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入用户名'))
    } else if (value.length < 5 || value.length > 10) {
        callback(new Error('用户名长度在5-10之间'))
    } else {
        callback()
    }
}
// 验证用户昵称
const validateName = (_rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入用户昵称'))
    } else if (value.length < 5 || value.length > 10) {
        callback(new Error('用户昵称长度在5-10之间'))
    } else {
        callback()
    }
}
// 验证用户密码
const validatePassword = (_rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入用户密码'))
    } else if (value.length < 5) {
        callback(new Error('用户密码长度至少有6位'))
    } else {
        callback()
    }
}
// 验证规则
const rules = ref({
    username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
    name: [{ required: true, validator: validateName, trigger: 'blur' }],
    password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
})
// 提交
const handleSubmit = useThrottle(async () => {
    await formRef.value.validate()
    while (true) {
        try {
            const res = await addorupdateUser(UserParams.value)
            if (res.code == 200) {
                ElMessage.success(UserParams.value.id ? '编辑成功' : '添加成功')
                clearUserParams()
                drawer.value = false
                getUserListData()
                break
            }
            else if (res.code == 201) {
                ElMessage.error(res.message)
                break
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}, 1000)
// 取消
const handleCancel = () => {
    clearUserParams()
    drawer.value = false
}
// 分配角色提交
const handleEditRoleSubmit = async () => {
    const setRoleData: SetRoleData = {
        userId: UserParams.value.id as number,
        roleIdList: hasRoleList.value.map(item => item.id)
    }
    while (true) {
        try {
            const res = await setRole(setRoleData)
            if (res.code == 200) {
                ElMessage.success('分配角色成功')
                drawer1.value = false
                getUserListData()
                break
            }
            else if (res.code == 201) {
                ElMessage.error(res.message)
                break
            }
        } catch (error) {
            ElMessage.error('请求失败，正在重试...');
        }
    }
}
const handleCheckAllChange = (val: CheckboxValueType) => {
    hasRoleList.value = val ? allRoleList.value : []
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === allRoleList.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRoleList.value.length
}
const handleSelectionChange = (selection: User[]) => {
    deleteidList.value = selection.map(item => item.id as number)
}
onMounted(() => {
    getUserListData()
})
watch([PageNo, pageSize], () => {
    getUserListData()
})
</script>
<style scoped lang="less">
.user-table {
    margin: 20px 0;
}
</style>
